package stud.mpgame.network;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

class UserObjectEncoder implements ProtocolEncoder {

    private static int serialNumberCnt = 0;
    private long startAppTime;
    private int protocolVersion;
    private int maxMessageBufferSize;

    UserObjectEncoder(long startAppTime, int protocolVersion, int maxMessageBufferSize) {
        this.startAppTime = startAppTime;
        this.protocolVersion = protocolVersion;
        this.maxMessageBufferSize = maxMessageBufferSize;
    }

    synchronized private void incrementSerialNumber() {
        serialNumberCnt++;
    }

    public void encode(IoSession ioSession, Object o, ProtocolEncoderOutput protocolEncoderOutput) throws Exception {
        if (o instanceof Message) {
            IoBuffer buffer = IoBuffer.allocate(maxMessageBufferSize);
            Message message = (Message) o;
            buffer.putInt(0); //length
            long currentTime = System.currentTimeMillis();
            int sentTime = (int) (currentTime - startAppTime);
            message.writeExternal(buffer, serialNumberCnt, sentTime, protocolVersion);
            incrementSerialNumber();
            buffer.flip();
            buffer.putInt(buffer.limit() - 4);
            buffer.position(0);
            protocolEncoderOutput.write(buffer);
        } else {
            throw new IllegalArgumentException("Class " + o.getClass() + " is not implementing the specified interface: stud.mpgame.server.mina.IUserObject (loaded object was of wrong class) ");
        }
    }

    public void dispose(IoSession ioSession) throws Exception {

    }
}
